<template>
  <el-dialog
    title="修改人员"
    :visible.sync="dialogVisible"
    :before-close="cancel"
    :close-on-click-modal="false"
    class="vc-dialog-form"
    width="780px">
    <el-form ref="editForm" class="personnel-form-top" :model="editForm" :rules="rules" label-width="90px" size="small">
      <div class="part-title">人员信息</div>

      <div class="form-top-left">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" maxlength="20" placeholder="请输入" clearable @clear="$refs.editForm.validateField('name')"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="editForm.tel" type="tel" maxlength="11" placeholder="请输入" clearable @clear="$refs.editForm.validateField('tel')"></el-input>
        </el-form-item>

        <el-form-item label="所属部门" prop="orgId">
          <el-tree-select
            v-model="editForm.orgId"
            :default-expanded-keys="orgTreeData.length ? [orgTreeData[0].id] : []"
            :data="orgTreeData"
            :props="defaultProps"
            clearable>
          </el-tree-select>
        </el-form-item>
      </div>

      <div class="form-top-center">
        <el-form-item label="性别" prop="sex" class="align-left">
          <el-radio v-model="editForm.sex" v-for="item in personSexList" :key="item.code" :label="item.code">{{ item.name }}</el-radio>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" type="email" maxlength="40" placeholder="请输入" clearable @clear="$refs.editForm.validateField('email')"></el-input>
        </el-form-item>

        <el-form-item label="入职时间" prop="hiredate">
          <el-date-picker
            v-model="editForm.hiredate"
            type="date"
            format="yyyy-MM-dd"
            value-format="timestamp"
            placeholder="请选择"
            :editable="false">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="用户ID" prop="userId" v-show="false">
          <el-input v-model="editForm.userId"></el-input>
        </el-form-item>
      </div>

      <div class="upload-head">
        <el-upload
          v-loading="loading"
          ref="addLeaderUpload"
          class="avatar-uploader"
          :action="`${serverData.url}/upload`"
          method="post"
          enctype="multipart/form-data"
          accept="image/*"
          :data="uploadData"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :show-file-list="false"
          :auto-upload="true">
          <template v-if="editForm.head">
            <img :src="editForm.head" :key="editForm.head"/>
            <div class="change-head-tip">
              <img src="../../../assets/img/upload.png"/>
              <div>更换头像</div>
            </div>
          </template>
          <template v-else>
            <img src="../../../assets/img/head-default.png"/>
            <div class="change-head-tip">
              <img src="../../../assets/img/upload.png"/>
              <div>添加头像</div>
            </div>
          </template>
          <div class="bottom-tips"><div>上限500K</div></div>
        </el-upload>
        <div v-if="editForm.head" class="head-del vc-icon vc-icon-del color-danger" title="删除头像" @click="delHead"></div>
      </div>
    </el-form>

    <div class="personnel-form-center">
      <el-button class="vc-icon vc-icon-selectUser" type="text" @click="selectUser">选择用户</el-button>
      <el-button class="vc-icon vc-icon-addUser" type="text" @click="addUser">新增用户</el-button>
      <el-button class="vc-icon vc-icon-clear" type="text" @click="clearUser" :disabled="!editForm.userId">清空用户</el-button>
    </div>

    <el-form ref="userEntity" class="personnel-form-bottom" id="userInfoOfEdit" :model="userEntity" label-width="90px" size="small" :disabled="true">
      <div>
        <div class="part-title">用户信息</div>

        <div>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userEntity.username"></el-input>
          </el-form-item>
          
          <el-form-item label="登录密码" prop="cipherCode">
            <el-input :value="GLOBAL.formatter.formatPwd(userEntity.cipherCode)"></el-input>
          </el-form-item>

          <el-form-item label="用户状态" prop="state">
            <el-input :value="userStateMap[userEntity.state]"></el-input>
          </el-form-item>
        </div>
        
        <div>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userEntity.nickname"></el-input>
          </el-form-item>

          <el-form-item label="用户类型" prop="type">
            <el-input :value="userTypeMap[userEntity.type]"></el-input>
          </el-form-item>

          <el-form-item label="用户性质" prop="nature">
            <el-input :value="userNatureMap[userEntity.nature]"></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button type="primary" size="small" :disabled="disabled" @click="save">保存</el-button>
    </span>
    
    <!-- 选择用户 -->
    <select-user ref="selectUserDialog" :dialogVisible="selectUserDialogVisible" :userId="editForm.userId" @close="closeSelectUserDialog"></select-user>
    
    <!-- 新增用户 -->
    <add-user ref="addUserDialog" :dialogVisible="addUserDialogVisible" :subComponent="true" @close="closeAddUserDialog"></add-user>
    
  </el-dialog>
</template>

<script>
import SelectUser from './selectUser';
import AddUser from '../user/add';
import { validateName, validateMobile, validateEmail } from '@/utils/validator';

export default {
  name: 'editPersonnel',
  components: { SelectUser, AddUser },
  props: ['dialogVisible', 'entity'],
  data() {
    return {
      editForm: {
        name: '',
        sex: '',
        tel: '',
        email: '',
        orgId: '',
        hiredate: '',
        head: '',
        userId: ''
      },
      head: '',
      userEntity: {
        username: '',
        nickname: '',
        cipherCode: '',
        type: '',
        state: '',
        nature: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ]
      },
      disabled: false,
      defaultProps: {
        id: 'id',
        label: 'name',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      selectUserDialogVisible: false,
      addUserDialogVisible: false,
      loading: false,
      uploadData: {
        appId: this.$store.state.config.data['wjfwyyid'],
        timestamp: '',
        sig: ''
      }
    }
  },
  computed: {
    serverData() {
      let data = this.$store.state.config.data;
      return {
        url: data['wjfwqdz'] + '/yfs',
        secret: data['wjfwyymy']
      };
    },
    orgTreeData() {
      return this.$parent.orgTreeSelect;
    },
    personSexList() {
      return this.$store.state.dic.listFormat['00001'];
    },
    userTypeMap() {
      return this.$store.state.dic.mapFormat['yhlx'] || {};
    },
    userStateMap() {
      return this.$store.state.dic.mapFormat['yhzt'] || {};
    },
    userNatureMap() {
      return this.$store.state.dic.mapFormat['yhxz'] || {};
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.loading = false;
        this.$refs.selectUserDialog.reset();
        $('#userInfoOfEdit').slideUp();
        return;
      }
      this.disabled = false;
    },
    entity: {
      handler(val) {
        this.init();
        this.$nextTick(() => { this.$refs.editForm && this.$refs.editForm.clearValidate(); });
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * 获取人员和用户信息
     */
    init() {
      this.entity && !this.entity.userId && (this.entity.userId = '');
      this.editForm.head = this.head = this.entity.head;
      this.editForm = Object.assign({}, this.entity);
      this.editForm.userId && this.$api.getUserById({
        data: {
          id: this.editForm.userId
        }
      }).then(res => {
        if (!res.success || !res.data) {
          return;
        }
        this.userEntity = res.data;
        this.userEntity.cipherCode = this.GLOBAL.formatter.formatPwd(this.userEntity.cipherCode);
        this.$nextTick(() => { $('#userInfoOfEdit').slideDown(0); });
      });
    },
    /**
     * 保存
     */
    save() {
      if (this.disabled) {
        return;
      }
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.disabled = true;
        let data = Object.assign({}, this.editForm);
        data.head = this.head;
        this.$api.updatePersonnel({
          data: data
        }).then(res => {
          if (!res.success) {
            this.disabled = false;
            if (res.code == '10220') {
              this.$parent.getAllOrg(this.$parent.id);
            }
            return;
          }
          this.$emit('close', res.data || {});
          this.$notifyBox('保存成功', 'success');
          res.data && res.data.userId === this.$store.state.user.userInfo.userId && this.$store.dispatch('getUserInfo');
        }).catch(() => {
          this.disabled = false;
        });
      });
    },
    /**
     * 取消
     */
    cancel() {
      this.$emit('close', false);
    },
    /**
     * '选择用户'按钮点击事件
     */
    selectUser() {
      this.selectUserDialogVisible = true;
    },
    /**
     * '选择用户'弹出框关闭事件
     */
    closeSelectUserDialog(val) {
      this.selectUserDialogVisible = false;
      if (!val) return;
      this.userEntity = Object.assign({}, val);
      this.editForm.userId = val.id;
      $('#userInfoOfEdit').slideDown();
      this.userEntity.cipherCode = this.GLOBAL.formatter.formatPwd(this.userEntity.cipherCode);
    },
    /**
     * '新增用户'按钮点击事件
     */
    addUser() {
      this.addUserDialogVisible = true;
    },
    /**
     * '新增用户'弹出框关闭事件
     */
    closeAddUserDialog(val) {
      this.addUserDialogVisible = false;
      if (!val) return;
      this.userEntity = Object.assign({}, val);
      this.editForm.userId = val.id;
      $('#userInfoOfEdit').slideDown();
    },
    /**
     * '清空用户'按钮点击事件
     */
    clearUser() {
      $('#userInfoOfEdit').slideUp();
      this.$refs.userEntity && this.$refs.userEntity.resetFields();
      this.editForm.userId = '';
    },
    /**
     * 上传文件之前的钩子
     */
    beforeUpload(file) {
      const limited = this.GLOBAL.upload.isLimited(file.size);
      if (!limited) {
        this.$notifyBox(this.GLOBAL.MSG.UPLOAD_EXCEED_SIZE);
        return false;
      }
      this.loading = true;
      let sha256 = require("js-sha256").sha256;
      this.uploadData.timestamp = Date.now();
      this.uploadData.sig = sha256(this.uploadData.appId + this.serverData.secret + this.uploadData.timestamp);
    },
    /**
     * 文件上传成功时的钩子
     */
    uploadSuccess(response, file) {
      if (!response.success) {
        this.handleCatch(response, this.GLOBAL.MSG.UPLOAD_ERR_MSG);
        return;
      }
      this.editForm.head = URL.createObjectURL(file.raw);
      this.head = `${this.serverData.url}/dl/${response.data}`;
      this.$nextTick(() => { this.loading = false; });
    },
    /**
     * 文件上传失败时的钩子
     */
    uploadError(err) {
      this.handleCatch(err, this.GLOBAL.MSG.UPLOAD_ERR_MSG);
    },
    /**
     * 捕获异常处理
     */
    handleCatch(err, msg = '') {
      this.loading = false;
      this.$notifyBox(msg, 'error');
      window.console && console.log(err);
    },
    /**
     * 删除头像
     */
    delHead() {
      this.editForm.head = null;
      this.head = '';
    }
  }
}
</script>